<?php

namespace AppBundle\Controller;

use AppBundle\Entity\Company;
use AppBundle\Entity\User;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Component\HttpFoundation\Request;

/**
 * 公司
 *
 * @Route("/company")
 */
class CompanyController extends Controller
{
    /**
     * 公司展示
     *
     * @Route("/", name="company_show")
     * @Method("GET")
     */
    public function showAction(Request $request)
    {
        /** @var  $session_user User*/
        $session_user = $request->getSession()->get('user');

        $em = $this->getDoctrine()->getManager();
        $company = $em->getRepository('AppBundle:Company')->find($session_user->getCompanyId());

        return $this->render('company/show.html.twig', [
            'company' => $company,
        ]);
    }

    /**
     * 编辑
     *
     * @Route("/edit", name="company_edit")
     * @Method({"GET", "POST"})
     */
    public function editAction(Request $request)
    {
        $session_user = $request->getSession()->get('user');

        $em = $this->getDoctrine()->getManager();
        $company = $em->getRepository('AppBundle:Company')->find($session_user->getCompanyId());

        $editForm = $this->createForm('AppBundle\Form\CompanyType', $company);
        $editForm->handleRequest($request);

        if ($editForm->isSubmitted() && $editForm->isValid()) {

            /** @var \Symfony\Component\HttpFoundation\File\UploadedFile $file */
            $file = $editForm->get('file')->getData();

            $fileName = md5(uniqid()).'.'.$file->guessExtension();

            $file->move($this->getParameter('upload_directory'),$fileName);
            $company->setLicenseBusinessPic($fileName);

            $em->persist($company);
            $em->flush();

            return $this->redirectToRoute('company_show');
        }

        return $this->render('company/edit.html.twig', [
            'company' => $company,
            'edit_form' => $editForm->createView(),
        ]);
    }


}
